package org.luxor.common.netty.jdk.aio.client.handler;

import org.luxor.common.netty.jdk.aio.client.AsyncTimeClientHandler;
import org.luxor.commons.core.utils.IoUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * 建立客户端连接成功之后的处理器
 *
 * @author Mr.yan @date 2023/9/3
 */
public class ConnectCompletionHandler implements CompletionHandler<Void, AsyncTimeClientHandler> {
    private static final Logger log = LoggerFactory.getLogger(ConnectCompletionHandler.class);

    @Override
    public void completed(Void result, AsyncTimeClientHandler attachment) {
        // 连接成功，发送时间查询请求
        byte[] req = "QUERY TIME ORDER".getBytes();
        ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
        writeBuffer.put(req);
        writeBuffer.flip();
        AsynchronousSocketChannel asyncSocketChannel = attachment.getClientAsyncSocketChannel();
        asyncSocketChannel.write(writeBuffer, writeBuffer, new ClientWriteCompletionHandler(attachment));
    }

    @Override
    public void failed(Throwable exc, AsyncTimeClientHandler attachment) {
        log.error("请求建立与服务端连接时,出现失败", exc);
        IoUtils.closeQuietly(attachment.getClientAsyncSocketChannel());
        attachment.getLatch().countDown();
    }
}
